<?php
namespace app\admin\logic;

use app\common\Constant;
use app\model\Admin;
use app\model\Log;
use app\model\Role;
use base\BaseLogic;

class AdminLogic extends BaseLogic
{
    /**
     * 添加管理员
     *
     * @param array $data
     * @return void
     */
    public function addAdmin($data)
    {
        $admin = new Admin();

        $data['salt'] =  mt_rand(1000,9999);

        $data['password'] = sha1($data['password'].$data['salt']);
        
        $res = $admin->save($data);

        if($res){
            return $admin->admin_id;
        }

        return_error(['info'=>'添加管理员失败']);
        
    }

    /**
     * 更新管理员信息
     *
     * @param [type] $admin_id
     * @param [type] $data
     * @return void
     */
    public function updateAdmin($admin_id,$data)
    {
        $admin = Admin::find($admin_id);

        if(!$admin){
            return_error(['info'=>'管理员不存在']);
        }

        $res = $admin->allowField(['admin_name','mobile','role_id','status'])->save($data);

        if($res){
            return true;
        }

        return_error(['info'=>'更新失败']);
    }

    /**
     * 删除失败
     *
     * @param [type] $admin_id
     * @return void
     */
    public function deleteAdmin($admin_id)
    {
        if($admin_id==Constant::SUPER_ADMIN){
            return_error(['info'=>'管理员不存在']);
        }

        $admin = Admin::find($admin_id);

        if(!$admin){
            return_error(['info'=>'管理员不存在']);
        }

        if($admin->type==Constant::SUPER_ADMIN_TYPE){
            return_error(['info'=>'内置管理员不能删除']);
        }

        $res = $admin->delete();

        if($res){
            return true;
        }

        return_error(['info'=>'删除失败']);
    }

    /**
     * 修改密码（登录人）
     *
     * @param [type] $admin_id
     * @param [type] $new_pass
     * @param [type] $old_pass
     * @return void
     */
    public function updatePass($admin_id,$new_pass,$old_pass)
    {
        $admin = Admin::find($admin_id);

        if(!$admin){
            return_error(['info'=>'管理员不存在']);
        }

        if(sha1($old_pass.$admin->salt)!=$admin->password){
            return_error(['info'=>'原密码错误!']);
        }

        $admin->password = sha1($new_pass.$admin->salt);

        $res = $admin->save();

        if($res){
            return true;
        }

        return_error(['info'=>'密码修改失败']);
    }

    /**
     * 重置密码
     *
     * @param [type] $admin_id
     * @param string $new_pass
     * @return void
     */
    public function resetPass($admin_id,$new_pass = '123456')
    {
        $admin = Admin::find($admin_id);

        if(!$admin){
            return_error(['info'=>'管理员不存在']);
        }

        $admin->password = sha1($new_pass.$admin->salt);

        $res = $admin->save();

        if($res){
            return true;
        }

        return_error(['info'=>'密码重置失败']);
    }

    /**
     * 获取管理员列表
     *
     * @param [type] $param
     * @param [type] $is_page
     * @return void
     */
    public function getAdminList($param,$is_page)
    {
        $wconfig=[
            'status'=>['status','='],
            'role_id'=>['role_id','='],
            'admin_name'=>['admin_name','like'],
            'mobile'=>['mobile','like']
        ];

        $admin = new Admin();

        $admin = $this->buildwhere($admin,$param,$wconfig)->where('admin_id','<>',Constant::SUPER_ADMIN);

        $admin = $admin->with('role');

        if($is_page){
            $data['list_rows']=$param['list_rows']??"15";
            $data['page']=$param['page']?? "1";
            $list = $admin->paginate($data);
        }else{
            $list = $admin->select();
        }

        return $list;

    }

    /**
     * 获取管理员信息
     *
     * @param integer $admin_id 管理员ID
     * @return void
     */
    public function getAdminInfo($admin_id)
    {
        $admin = Admin::with('priv')->find($admin_id);

        if(!$admin){
            return_error(['info'=>'管理员不存在!']);
        }

        return $admin->toArray();
    }

    /**
     * 添加职位
     *
     * @param array $data
     * @return void
     */
    public function addRole($data)
    {   
        $role = new Role();

        //list($data['menu'],$data['api'])=$this->parsePriv($data['priv_ids']);

        if(isset($data['menu'])&&is_array($data['menu'])){
            $data['menu']=json_encode($data['menu']);
        }

        if(isset($data['api'])&&is_array($data['api'])){
        
            $data['api']=json_encode($data['api']);

        }

        $res = $role->save($data);

        if($res){
            return $role->role_id;
        }

        return_error(['info'=>'添加职位失败']);

    }

    /**
     * 格式化权限字符串，待做
     *
     * @param [type] $priv_ids
     * @return void
     */
    private function parsePriv($priv_ids)
    {
        //todo
        return ['menu'=>[],'api'=>[]];
    }

    /**
     * 更新职位
     *
     * @param integer $role_id
     * @param array $data
     * @return void
     */
    public function updateRole($role_id,$data)
    {
        $role = Role::find($role_id);

        if(!$role){
            return_error(['info'=>'职位不存在']);
        }

        if(isset($data['menu'])&&is_array($data['menu'])){
            $data['menu']=json_encode($data['menu']);
        }

        if(isset($data['api'])&&is_array($data['api'])){
        
            $data['api']=json_encode($data['api']);

        }

        $res = $role->allowField(['role_name','role_desc','menu','api','status'])->save($data);

        if($res){
            return true;
        }

        return_error(['info'=>'更新失败']);
    }

    /**
     * 删除职位
     *
     * @param [type] $role_id
     * @return void
     */
    public function deleteRole($role_id)
    {
        if($role_id==Constant::SUPER_ROLE){
            return_error(['info'=>'角色不存在']);
        }

        $role = Role::find($role_id);

        if(!$role){
            return_error(['info'=>'职位不存在']);
        }

        if($role->type==Constant::SUPER_ROLE_TYPE){
            return_error(['info'=>'内置角色不能删除']);
        }

        $res = $role->delete();

        if($res){
            return true;
        }

        return_error(['info'=>'删除失败']);
    }

    /**
     * 获取职位列表
     *
     * @param [type] $param
     * @param [type] $is_page
     * @return void
     */
    public function getRoleList($param,$is_page)
    {
        $wconfig=[
            'status'=>['status','='],
            'role_name'=>['role_name','like']
        ];
        $role = new Role();

        $role = $this->buildwhere($role,$param,$wconfig)->where('role_id','<>',Constant::SUPER_ROLE);

        if($is_page){
            $data['list_rows']=$param['list_rows']??"15";
            $data['page']=$param['page']?? "1";
            $list = $role->paginate($data);
        }else{
            $list = $role->select();
        }

        return $list;
    }

    /**
     * 获取职位信息
     *
     * @param [type] $role_id
     * @return void
     */
    public function getRoleInfo($role_id)
    {
        $role = Role::find($role_id);

        if(!$role){
            return false;
        }

        return $role->toArray();
    }

    /**
     * 获取日志相关配置列表
     *
     * @param string $type
     * @return void
     */
    public function getLogConfig($type)
    {
        $config = config('oplog');
        $res = [];
        switch ($type) {
            case 'app':       
                foreach ($config as $key => $value) {
                    $res[$key]=$value['appname'];
                }
                break;
            case 'module':
                foreach ($config as $key => $value) {
                    $res = array_merge($res,$value['module']??[]);
                }
                break;

            case 'type':
                
                return ["0"=>'其他',"1"=>'新增','2'=>'删除','3'=>'修改','4'=>'查询'];

                break;
            
            default:
                return_error(['info'=>'未定义配置类型']);
                break;
        }

        return $res;
    }

    /**
     * 获取日志列表
     *
     * @param [type] $param
     * @param [type] $is_page
     * @return void
     */
    public function getLogList($param,$is_page){
        $wconfig = [
            'create_time'=>['create_time','time'],
            'app'=>['app','='],
            'module'=>['module','='],
            'type'=>['type','='],
            'title'=>['title','like'],
            'is_display'=>['is_display','=']
        ];

        $param['is_display']=1;
        
        $log = $this->buildwhere(new Log(),$param,$wconfig);

        if($is_page){
            $page['page']=$param['page']??1;
            $page['list_rows']=$param['list_rows']??15;

            $list = $log->paginate($page);
        }else{
            $list = $log->select();
        }

        return $list;

    }
}